<template>
  <div class="order-list-container">
    <div class="page-header">
      <h2>我的订单</h2>
    </div>

    <!-- 订单状态筛选 -->
    <div class="order-tabs">
      <el-tabs v-model="activeTab" type="card" @tab-click="handleTabClick">
        <el-tab-pane label="全部订单" name="all">
          <template #label>
            <span>全部订单</span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="待付款" name="pendingPayment">
          <template #label>
            <span>待付款</span>
            <el-badge v-if="pendingCount > 0" :value="pendingCount" class="order-badge" />
          </template>
        </el-tab-pane>
        <el-tab-pane label="待发货" name="pendingShipment">
          <template #label>
            <span>待发货</span>
            <el-badge v-if="shippingCount > 0" :value="shippingCount" class="order-badge" />
          </template>
        </el-tab-pane>
        <el-tab-pane label="待收货" name="pendingReceipt">
          <template #label>
            <span>待收货</span>
            <el-badge v-if="receiptCount > 0" :value="receiptCount" class="order-badge" />
          </template>
        </el-tab-pane>
        <el-tab-pane label="已完成" name="completed">
          <template #label>
            <span>已完成</span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="已取消" name="cancelled">
          <template #label>
            <span>已取消</span>
          </template>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 订单列表 -->
    <el-card v-loading="isLoading" class="order-card" v-for="order in filteredOrders" :key="order.id">
      <!-- 订单头部信息 -->
      <div class="order-header">
        <div class="order-info">
          <span class="order-id">订单号: {{ order.id }}</span>
          <span class="order-date">下单时间: {{ formatDate(order.createdAt) }}</span>
        </div>
        <div class="order-status" :class="'status-' + order.status">
          {{ getStatusText(order.status) }}
        </div>
      </div>
      
      <!-- 订单商品列表 -->
      <div class="order-products">
        <div 
          class="order-product-item" 
          v-for="item in order.items" 
          :key="item.id"
          @click="goToProductDetail(item.id)"
        >
          <img :src="item.image" alt="商品图片" class="product-image">
          <div class="product-info">
            <div class="product-title">{{ item.title }}</div>
            <div class="product-price">¥{{ item.price.toFixed(2) }}</div>
            <div class="product-quantity">x{{ item.quantity }}</div>
          </div>
        </div>
      </div>
      
      <!-- 收货地址信息 -->
      <div class="shipping-info">
        <div class="shipping-label">收货信息：</div>
        <div class="shipping-detail">
          {{ order.address.name }} {{ order.address.phone }} | {{ order.address.province }} {{ order.address.city }} {{ order.address.district }} {{ order.address.detailAddress }}
        </div>
      </div>
      
      <!-- 订单底部 -->
      <div class="order-footer">
        <div class="order-amount">
          共 {{ getTotalQuantity(order) }} 件商品，合计：
          <span class="total-price">¥{{ order.totalAmount.toFixed(2) }}</span>
        </div>
        
        <div class="order-actions">
          <template v-if="order.status === 'pendingPayment'">
            <el-button size="small" @click="cancelOrder(order.id)">取消订单</el-button>
            <el-button type="primary" size="small" @click="payOrder(order.id)">去付款</el-button>
          </template>
          
          <template v-else-if="order.status === 'pendingShipment'">
            <el-button size="small" @click="contactSeller(order.id)">联系卖家</el-button>
          </template>
          
          <template v-else-if="order.status === 'pendingReceipt'">
            <el-button size="small" @click="checkLogistics(order.id)">查看物流</el-button>
            <el-button type="primary" size="small" @click="confirmReceipt(order.id)">确认收货</el-button>
          </template>
          
          <template v-else-if="order.status === 'completed'">
            <el-button size="small" @click="reviewOrder(order.id)">评价</el-button>
            <el-button size="small" @click="contactSeller(order.id)">联系卖家</el-button>
            <el-button size="small" @click="rebuy(order.id)">再次购买</el-button>
          </template>
          
          <template v-else-if="order.status === 'cancelled'">
            <el-button size="small" @click="rebuy(order.id)">再次购买</el-button>
            <el-button size="small" type="danger" @click="deleteOrder(order.id)">删除订单</el-button>
          </template>
        </div>
      </div>
    </el-card>

    <!-- 空状态 -->
    <div v-if="!isLoading && filteredOrders.length === 0" class="empty-orders">
      <el-empty description="暂无订单">
        <template #image>
          <el-icon><i-ep-document /></el-icon>
        </template>
        <el-button type="primary" @click="goShopping">去购物</el-button>
      </el-empty>
    </div>

    <!-- 分页 -->
    <div v-if="filteredOrders.length > 0" class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useOrderStore } from '../../store'
import dayjs from 'dayjs'

const router = useRouter()
const orderStore = useOrderStore()

const isLoading = ref(false)
const activeTab = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)

// 订单统计数量
const pendingCount = ref(0)
const shippingCount = ref(0)
const receiptCount = ref(0)

// 模拟订单数据
const orders = ref([
  {
    id: '202311110001',
    createdAt: '2023-11-11 10:30:45',
    status: 'pendingPayment',
    items: [
      {
        id: '101',
        title: '全新 小米13 8+256G 黑色 国行正品',
        image: '/images/phone1.jpg',
        price: 3599,
        quantity: 1
      }
    ],
    address: {
      name: '张三',
      phone: '13800138000',
      province: '北京市',
      city: '北京市',
      district: '海淀区',
      detailAddress: '北京大学 1号公寓 301室'
    },
    subtotal: 3599,
    shippingFee: 0,
    totalAmount: 3599
  },
  {
    id: '202311100002',
    createdAt: '2023-11-10 15:20:18',
    status: 'pendingShipment',
    items: [
      {
        id: '202',
        title: 'MacBook Pro 2022 14英寸 M2 Pro芯片',
        image: '/images/laptop1.jpg',
        price: 14999,
        quantity: 1
      },
      {
        id: '203',
        title: 'Apple Magic Mouse 2 无线鼠标',
        image: '/images/mouse1.jpg',
        price: 549,
        quantity: 1
      }
    ],
    address: {
      name: '李四',
      phone: '13900139000',
      province: '上海市',
      city: '上海市',
      district: '浦东新区',
      detailAddress: '复旦大学 2号教学楼 501室'
    },
    subtotal: 15548,
    shippingFee: 0,
    totalAmount: 15548
  },
  {
    id: '202311090003',
    createdAt: '2023-11-09 09:15:30',
    status: 'pendingReceipt',
    items: [
      {
        id: '301',
        title: 'Nike Air Force 1 空军一号 白色',
        image: '/images/shoes1.jpg',
        price: 799,
        quantity: 1
      }
    ],
    address: {
      name: '王五',
      phone: '13700137000',
      province: '广州市',
      city: '广州市',
      district: '天河区',
      detailAddress: '中山大学 北区宿舍 4栋 202室'
    },
    subtotal: 799,
    shippingFee: 10,
    totalAmount: 809
  },
  {
    id: '202311080004',
    createdAt: '2023-11-08 20:45:12',
    status: 'completed',
    items: [
      {
        id: '401',
        title: '全新 华为 MateBook X Pro 13.9英寸',
        image: '/images/laptop2.jpg',
        price: 8999,
        quantity: 1
      }
    ],
    address: {
      name: '赵六',
      phone: '13600136000',
      province: '深圳市',
      city: '深圳市',
      district: '南山区',
      detailAddress: '深圳大学 南区 12栋 505室'
    },
    subtotal: 8999,
    shippingFee: 0,
    totalAmount: 8999
  },
  {
    id: '202311070005',
    createdAt: '2023-11-07 14:10:20',
    status: 'cancelled',
    items: [
      {
        id: '501',
        title: 'iPad Pro 2022 11英寸 256G',
        image: '/images/ipad1.jpg',
        price: 6799,
        quantity: 1
      }
    ],
    address: {
      name: '孙七',
      phone: '13500135000',
      province: '成都市',
      city: '成都市',
      district: '武侯区',
      detailAddress: '四川大学 望江校区 10号楼 301室'
    },
    subtotal: 6799,
    shippingFee: 0,
    totalAmount: 6799
  }
])

onMounted(() => {
  loadOrders()
})

const loadOrders = async () => {
  isLoading.value = true
  
  try {
    // 在实际项目中，这里应该从API获取订单数据
    // await orderStore.fetchOrders()
    
    // 模拟计算订单数量
    calculateOrderCounts()
  } catch (error) {
    ElMessage.error('加载订单失败，请稍后重试')
    console.error('加载订单失败:', error)
  } finally {
    isLoading.value = false
  }
}

const calculateOrderCounts = () => {
  pendingCount.value = orders.value.filter(o => o.status === 'pendingPayment').length
  shippingCount.value = orders.value.filter(o => o.status === 'pendingShipment').length
  receiptCount.value = orders.value.filter(o => o.status === 'pendingReceipt').length
}

// 根据当前选中的标签过滤订单
const filteredOrders = computed(() => {
  if (activeTab.value === 'all') {
    return orders.value
  }
  return orders.value.filter(order => order.status === activeTab.value)
})

// 订单总数
const total = computed(() => filteredOrders.value.length)

const handleTabClick = () => {
  currentPage.value = 1 // 切换标签时重置为第一页
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}

const formatDate = (dateString) => {
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss')
}

const getStatusText = (status) => {
  const statusMap = {
    pendingPayment: '待付款',
    pendingShipment: '待发货',
    pendingReceipt: '待收货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || '未知状态'
}

const getTotalQuantity = (order) => {
  return order.items.reduce((total, item) => total + item.quantity, 0)
}

const goToProductDetail = (productId) => {
  router.push(`/product/${productId}`)
}

const goShopping = () => {
  router.push('/products')
}

const cancelOrder = async (orderId) => {
  try {
    await ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 在实际项目中，这里应该调用API取消订单
    const order = orders.value.find(o => o.id === orderId)
    if (order) {
      order.status = 'cancelled'
      calculateOrderCounts()
      ElMessage.success('订单已取消')
    }
  } catch (error) {
    // 用户取消操作，不做任何处理
  }
}

const payOrder = (orderId) => {
  router.push(`/order/pay/${orderId}`)
}

const contactSeller = (orderId) => {
  ElMessage.info('正在跳转到聊天页面...')
  // 实际项目中应该跳转到与卖家的聊天页面
}

const checkLogistics = (orderId) => {
  ElMessage.info('正在查询物流信息...')
  // 实际项目中应该显示物流详情
}

const confirmReceipt = async (orderId) => {
  try {
    await ElMessageBox.confirm('确认已收到商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 在实际项目中，这里应该调用API确认收货
    const order = orders.value.find(o => o.id === orderId)
    if (order) {
      order.status = 'completed'
      calculateOrderCounts()
      ElMessage.success('已确认收货')
    }
  } catch (error) {
    // 用户取消操作，不做任何处理
  }
}

const reviewOrder = (orderId) => {
  ElMessage.info('跳转到评价页面...')
  // 实际项目中应该跳转到评价页面
}

const rebuy = (orderId) => {
  const order = orders.value.find(o => o.id === orderId)
  if (order) {
    // 将商品添加到购物车
    order.items.forEach(item => {
      // 实际项目中应该调用添加到购物车的API
    })
    ElMessage.success('商品已加入购物车')
    router.push('/cart')
  }
}

const deleteOrder = async (orderId) => {
  try {
    await ElMessageBox.confirm('确定要删除该订单吗？删除后不可恢复', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'danger'
    })
    
    // 在实际项目中，这里应该调用API删除订单
    const index = orders.value.findIndex(o => o.id === orderId)
    if (index !== -1) {
      orders.value.splice(index, 1)
      calculateOrderCounts()
      ElMessage.success('订单已删除')
    }
  } catch (error) {
    // 用户取消操作，不做任何处理
  }
}
</script>

<style scoped>
.order-list-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h2 {
  font-size: 24px;
  color: #333;
}

.order-tabs {
  margin-bottom: 20px;
}

.order-badge {
  margin-left: 5px;
}

.order-card {
  margin-bottom: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #e0e0e0;
}

.order-info {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #666;
}

.order-status {
  font-size: 14px;
  font-weight: bold;
}

.status-pendingPayment {
  color: #ff9800;
}

.status-pendingShipment {
  color: #2196f3;
}

.status-pendingReceipt {
  color: #8bc34a;
}

.status-completed {
  color: #4caf50;
}

.status-cancelled {
  color: #9e9e9e;
}

.order-products {
  padding: 20px 0;
  border-bottom: 1px solid #e0e0e0;
}

.order-product-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  cursor: pointer;
  transition: all 0.3s;
}

.order-product-item:hover {
  background: #f5f5f5;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 15px;
}

.product-info {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.product-title {
  flex: 1;
  font-size: 14px;
  color: #333;
  margin-right: 20px;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-price {
  color: #ff4d4f;
  font-weight: bold;
  margin-right: 20px;
}

.product-quantity {
  color: #999;
}

.shipping-info {
  padding: 15px 0;
  border-bottom: 1px solid #e0e0e0;
  font-size: 14px;
  color: #666;
}

.shipping-label {
  font-weight: bold;
  margin-bottom: 5px;
}

.shipping-detail {
  margin-left: 20px;
  line-height: 1.5;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0 0 0;
}

.order-amount {
  font-size: 16px;
  color: #333;
}

.total-price {
  font-size: 18px;
  font-weight: bold;
  color: #ff4d4f;
  margin-left: 10px;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.empty-orders {
  padding: 60px 0;
  text-align: center;
}

.empty-orders .el-icon {
  font-size: 100px;
  color: #e0e0e0;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .order-info {
    flex-direction: column;
    gap: 5px;
  }
  
  .product-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .product-title {
    margin-right: 0;
  }
  
  .shipping-detail {
    margin-left: 0;
  }
  
  .order-footer {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }
  
  .order-actions {
    justify-content: flex-end;
    flex-wrap: wrap;
  }
}
</style>